package com.pernix.authen.net;

import java.io.IOException;

import com.pernix.log.ConsoleLogging;
import com.pernix.log.ILog;

public class AuthenClient {
	int portNumber = 1500;
	String serverAddress = "localhost";
	String userName = "Anonymous";
	Client client;
	ILog logger;

	public AuthenClient(String serverAddr, int portNumber, ILog logger) {
		this.serverAddress = serverAddr;
		this.portNumber = portNumber;
		this.client = new Client(serverAddr, portNumber, logger);
		this.logger = logger;
	}

	public void Disconnect() {
		try {
			client.getSocket().close();
			client.disconnect();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public boolean authen(String username, String password) {
		boolean isFinish = false;
		client.setUsername(username);
		client.setPassword(password);
		if (client.start()) {
			logger.Info(String.format("Connect to Server %s:%s Completed.",
					serverAddress, portNumber));
			client.sendMessage(new ChatMessage(ChatMessage.REQ_SERVER_CHALLENGE,"request authen challenge"));
			logger.Info("Send=>REQ_SERVER_CHALLENGE to Server");
			while (client.isAuthenProcess()) {
				try {
					Thread.sleep(1);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			 System.out.println("Completed 8888888888888888888");
			// try {
			// client.getSocket().close();
			// } catch (IOException e) {
			// // TODO Auto-generated catch block
			// e.printStackTrace();
			// }
			// client.getListenFromServer().destroy();
			// client.disconnect();

		} else {
			logger.Info(String.format("Connect to Server %s:%s Fail.",
					serverAddress, portNumber));
		}
		return client.isVerify();
	}

	public void Close() {
		// client.disconnect();
		// client.getListenFromServer().stop();
		// client.getListenFromServer().destroy();
		//
		// try {
		// client.getSocket().close();
		// } catch (IOException e) {
		// // TODO Auto-generated catch block
		// e.printStackTrace();
		// }
	}

	public static void main(String[] args) {
		ConsoleLogging logger = new ConsoleLogging();
		AuthenClient authenClient = new AuthenClient("127.0.0.1", 1812, logger);
		boolean result = authenClient.authen("Kookkai", "Aa123456");
		System.out.println("result : " + result);
		System.out.println("Authen End.");
	}
}
